package ysq.xyg.base.util;

import com.baidu.aip.ocr.AipOcr;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * 单例获取百度图片文字识别
 *
 * @author taocongcong
 * @create 2019-05-05 9:23
 */
public class AipSingleton {

    private final static String APP_ID = "16436056";

    private final static String APP_KEY = "evhhkNEfE0yYMI0goRuEA8sD";

    private final static String SECRET_KEY = "8ZrjFW5xlSuWDWNOW3bx8yXgOhUBxzvu";

    private static AipOcr aipOcr;

    public static AipOcr getAipOcrInstance() {
        try {
            if (null == aipOcr) {
                synchronized (AipOcr.class) {
                    if(null == aipOcr) {
                        aipOcr = new AipOcr(APP_ID, APP_KEY, SECRET_KEY);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aipOcr;
    }
    public static JSONObject acceptText(AipOcr aipOcr,String url) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("language_type", "CHN_ENG");
        options.put("detect_direction", "true");
        options.put("detect_language", "true");
        options.put("probability", "true");
        // 参数为本地路径
       /* String image = "C:\\logs\\mmexport1557017929937.jpg";*/
        JSONObject res = aipOcr.basicGeneral(url, options);
        // 通用文字识别, 图片参数为远程url图片
        //JSONObject res = aipOcr.basicGeneralUrl(url, options);
       return res;
    }
    public static JSONObject acceptQrcode(AipOcr client,String url) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        // 参数为本地路径
        JSONObject res = client.qrcode(url, options);
        System.out.println(res.toString(2));
        return res;
    }

    public static void main(String[] args){
        JSONObject res = AipSingleton.acceptQrcode(AipSingleton.getAipOcrInstance(),"E:\\test\\2.jpg");
        int num=res.getInt("codes_result_num");
        JSONArray codesResult = res.getJSONArray("codes_result");
        JSONArray resultList=codesResult.getJSONObject(0).getJSONArray("text");
        String result="";
        if(resultList!=null&&resultList.length()>0){
            for(int i=0;i<resultList.length();i++){
                String j=resultList.get(i).toString();
                if(i==0){
                    result=j;
                }else{
                    result+=","+j;
                }
            }
        }
        System.out.println(result);
    }
}
